<!--  -->
<template>
  <div class="app-main-container">
    <div class="app-main-title">{{ managerName }}
      <div class="goback" @click="goBack">
        <i class="el-icon-refresh-left" /> 返回上一页
      </div>
    </div>
    <div>
      <el-form
        ref="form"
        class="doumee-form"
        :model="param"
        :rules="rules"
        label-width="140px"
        label-suffix="："
      >
        <div class="property-title">菜品信息</div>
        <el-form-item label="菜品图片" prop="picture">
          <transition name="fade">
            <Cropper
              v-if="dialogCropperVisible"
              :option-img="optionImg"
              :fileinfo="fileinfo"
              use-type="GOODS_IMG"
              :fixed-number="[32, 32]"
              @formSubmit="cropperSubmit"
              @formClose="cropperClose"
            />
          </transition>
          <div class="df_ac">
            <el-upload
              class="device-uploader"
              accept=".jpg,.png"
              :auto-upload="false"
              :action="uploadFileUrl"
              :data="uploadParam"
              :show-file-list="false"
              :on-change="addFileChange"
            >
              <i class="el-icon-plus uploader-icon" />
              <div
                v-show="param.showPoster"
                class="file"
                :style="'background-image: url(' + param.showPoster + ')'"
              >
                <div class="delete">
                  <i
                    class="el-icon-delete icon"
                    @click.stop="deleteDeviceConfigAddImage"
                  />
                </div>
              </div>
            </el-upload>
            <span class="el-upload__tip">jpg/png文件，单张</span>
          </div>

        </el-form-item>
        <el-form-item label="菜品名称" prop="name">
          <el-input v-model="param.name" class="w400" placeholder="请输入菜品名称" />
        </el-form-item>
        <el-form-item label="条形码" prop="barCode">
          <el-input v-model="param.barCode" class="w400" placeholder="请输入条形码" />
        </el-form-item>
        <el-form-item label="菜品分类" class="select-style" prop="classifyId">
          <el-select v-model="param.classifyId" class="w400" placeholder="选择菜品分类">
            <el-option
              v-for="item in typeList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="菜品库存" prop="stock">
          <el-input
            v-model="param.stock"
            class="w400"
            onkeyup="value=value.replace(/[^\d^\.]/g,'')"
            onkeypress="return event.keyCode>=48&&event.keyCode<=57"
            oninput="if(value<=0) { value = ''}"
            placeholder="请输入菜品库存"
          />
        </el-form-item>
        <el-form-item label="菜品价格" prop="price">
          <el-input
            v-model="param.price"
            class="w400"
            onkeyup="value=value.replace(/[^\d^\.]/g,'')"
            oninput="if(value<0) { value = ''}"
            placeholder="请输入菜品价格"
          />
        </el-form-item>
        <el-form-item label="菜品规格" class="select-style">
          <el-select v-model="param.goodsSkuIds" class="w400" multiple placeholder="选择菜品分类">
            <el-option
              v-for="item in skuNameList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item class="form-inline" label="是否上架">
          <el-switch
            v-model="isOn"
          />
        </el-form-item>
        <el-form-item label="菜品详情" prop="info">
          <el-input
            v-model="param.info"
            :rows="5"
            type="textarea"
            placeholder="请输入菜品介绍"
          />
        </el-form-item>
        <div class="property-title">会员折扣</div>
        <el-form-item label="折扣类型" class="select-style" prop="discountType">
          <el-select v-model="param.discountType" class="w400" placeholder="请选择折扣类型">
            <el-option
              v-for="item in discountType"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <div v-if="param.discountType == '1'" style="display: flex; flex-wrap: wrap">
          <el-form-item
            v-for="vip in vipTypeList"
            :key="vip.id"
            align="center"
            :label="vip.cardName"
            :prop="`discountMap.${vip.id}`"
            :rules="{ required: true, message: '请输入会员折扣', trigger: 'blur' }"
          >
            <el-input
              v-model="param.discountMap[vip.id]"
              onkeyup="value=value.replace(/[^\d.]/g, '').replace(/\.{2,}/g, '.').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3').replace(/^\./g, '')"
              oninput="if(value<0||value>1) { value = ''} else {value=value.replace(/[^\d.]/g, '').replace(/\.{2,}/g, '.').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3').replace(/^\./g, '')}"
              type="text"
              class="w400"
              placeholder="请输入会员折扣(保留两位小数)"
              maxlength="20"
            />
          </el-form-item>
        </div>
        <el-form-item>
          <el-button v-preventReClick :loading="subLoading" type="primary" @click="onSubmit()">提交</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import Cropper from '@/components/cropper'
import {
  uploadFile,
  goodsClassifyListVenue,
  cardList,
  goodsSave,
  goodsEditQuery,
  goodsEditSave,
  goodsSkuNameList
} from '@/api'
export default {
  name: 'VarietyAdd',
  components: {
    Cropper
  },
  data() {
    return {
      goodsRestaurantId: '',
      subLoading: false,
      listLoading: true,
      dialogCropperVisible: false,
      optionImg: '',
      files: {},
      fileinfo: {},
      swiperOptions: {
        slidesPerView: 'auto',
        pagination: {
          el: '.swiper-pagination'
        }
      },
      managerName: '',
      logoList: [],
      uploadParam: {
        folder: 'GOODS_IMG'
      },
      typeList: [],
      vipTypeList: [],
      uploadFileUrl: uploadFile,
      discountType: [
        { value: '0', label: '默认折扣' },
        { value: '1', label: '自定义折扣' }
      ],
      isOn: false,
      param: {
        venueId: sessionStorage.getItem('venueId'),
        saleType: 1,
        goodsRestaurantId: '',
        discountMap: {},
        goodsSkuIds: []
      },
      rules: {
        picture: [
          { required: true, message: '请上传菜品图片', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入菜品名称', trigger: 'blur' }
        ],
        // barCode: [
        //   { required: true, message: '请输入菜品条形码', trigger: 'blur' }
        // ],
        classifyId: [
          { required: true, message: '请选择菜品分类', trigger: 'blur' }
        ],
        // stock: [
        //   { required: true, message: '请输入菜品库存', trigger: 'blur' }
        // ],
        price: [
          { required: true, message: '请输入菜品价格', trigger: 'blur' }
        ],
        // info: [
        //   { required: true, message: '请输入菜品介绍', trigger: 'blur' }
        // ],
        discountType: [
          { required: true, message: '请选择折扣类型', trigger: 'change' }
        ]
      },
      skuNameList: []
    }
  },
  beforeRouteEnter(to, from, next) {
    // 在渲染该组件的对应路由被验证前调用
    // 不能获取组件实例 `this` ！
    // 因为当守卫执行时，组件实例还没被创建！
    to.meta.title = to.query.id ? '编辑菜品' : '新增菜品'
    next()
  },
  created() {
    this.goodsRestaurantId = this.$route.query.goodsRestaurantId || ''
    if (this.$route.query.id) {
      this.managerName = '编辑菜品'
      this.getClassifyList()
      this.getGoodsDetailInfo(this.$route.query.id)
    } else {
      this.managerName = '新增菜品'
      this.getClassifyList()
      this.getCardList()
    }
    goodsSkuNameList({
      param: {
        venueId: sessionStorage.getItem('venueId'),
        saleType: 1,
        goodsRestaurantId: this.goodsRestaurantId
      }
    })
      .then(res => {
        // console.log(res);
        if (res.errorCode === '000000') {
          this.skuNameList = res.recordList
        }
      })
  },
  methods: {
    getGoodsDetailInfo(id) {
      Promise.all([
        // 获取卡类型列表
        cardList({
          param: {
            cardName: null,
            isnormal: null,
            channel: null
          }
        }),
        goodsEditQuery({
          param: {
            id
          }
        })
      ])
        .then((res) => {
          this.vipTypeList = res[0].recordList
          this.param = res[1].record
          this.$set(this.param, 'showPoster', res[1].record.showPicture)
          this.$set(this.param, 'poster', res[1].record.picture)
          this.param.picture = res[1].record.picture
          this.isOn = this.param.status === '1'
          // console.log(this.param.goodsSkuIds.length);
          const goodsSkuIds = res[1].record.goodsSkuIds && res[1].record.goodsSkuIds.length > 0 ? res[1].record.goodsSkuIds.split(',') : []
          this.$set(this.param, 'goodsSkuIds', goodsSkuIds)
          // console.log(this.param);
          const discountmap = res[1].record.discountMap
          if (res[1].record.discountType === '0') {
            this.$set(this.param, 'discountMap', {})
          } else {
            this.$set(this.param, 'discountMap', discountmap)
          }
        })
    },
    getCardList() {
      // 获取卡类型列表
      cardList({})
        .then((res) => {
          if (res.errorCode === '000000') {
            this.vipTypeList = res.recordList
            const map = res.recordList
            map.map((item) => {
              item.set('creator', '')
            })
          }
        })
        .catch((err) => {
          console.log(err)
        })
    },
    // 场馆端菜品分类列表
    getClassifyList() {
      goodsClassifyListVenue({
        param: {
          venueId: sessionStorage.getItem('venueId'),
          saleType: 1,
          goodsRestaurantId: this.goodsRestaurantId
        }
      })
        .then((res) => {
          this.listLoading = false
          if (res.errorCode !== '000000') return
          this.typeList = res.recordList
        })
        .catch(() => {
          this.listLoading = false
        })
    },
    showGoodsImage() {
      const imageList = []
      if (this.param.showPicture) {
        imageList.push({
          url: this.param.showPicture,
          response: {
            insertUrl: this.param.picture,
            showUrl: this.param.showPicture
          }
        })
        this.logoList = [this.param.picture]
      }
      this.logoList = imageList
    },
    onlyDecimal(that, maxLen) {
      var reg = /^(([1-9][0-9]*)|(([0].\d{0,2}|[1-9][0-9]*.\d{0,2})))$/
      if (that.value.length === 1) {
        that.value = that.value.replace(/[^0-9]/g, '')
      } else {
        if (!reg.test(that.value)) {
          that.value = ''
        }
      }

      if (!(typeof maxLen === 'undefined' || maxLen === '' || maxLen == null) && that.value.length > maxLen) {
        var val = that.value
        that.value = val.toString().substring(0, parseInt(maxLen))
      }
    },
    // 菜品图片上传成功
    uploadSuccess(response, file, fileList) {
      this.param.picture = fileList[0].response.insertUrl
      this.$refs.form.clearValidate()
    },
    // 上传图片，开始裁剪
    async addFileChange(file) {
      // 上传，拿到file文件
      this.files = file.raw
      this.$nextTick(() => {
        this.optionImg = URL.createObjectURL(file.raw)
        this.fileinfo = file.raw
        this.dialogCropperVisible = true
      })
    },
    // 裁剪确定按钮
    cropperSubmit(config) {
      // preImg 完整路径  urlPre 不包含域名
      if (config.success) {
        this.$set(this.param, 'showPoster', config.showUrl)
        this.$set(this.param, 'poster', config.insertUrl)
        this.param.picture = config.insertUrl
        this.fileinfo = config
        // this.$refs.ruleForm.clearValidate();
        this.dialogCropperVisible = false
      } else {
        this.$message.error(config.msg || '上传失败')
        this.$refs.form.clearValidate()
        this.dialogCropperVisible = false
      }
    },
    // 裁剪取消
    cropperClose() {
      this.dialogCropperVisible = false
    },
    // 菜品图片移除
    deleteDeviceConfigAddImage(file, fileList) {
      this.$set(this.param, 'showPoster', '')
      this.$set(this.param, 'poster', '')
      this.param.picture = ''
    },
    onSubmit() {
      const param = { ...this.param }
      param.status = this.isOn ? '1' : '0'
      param.venueId = sessionStorage.getItem('venueId')
      param.goodsRestaurantId = this.goodsRestaurantId
      param.goodsSkuIds = this.param.goodsSkuIds.join(',') || ''
      if (this.$route.query.id) {
        this.$refs.form.validate((valid) => {
          if (valid) {
            this.subLoading = true
            goodsEditSave({
              param
            })
              .then((res) => {
                if (res.errorCode !== '000000') return
                this.subLoading = false
                this.$message.success('编辑成功')
                this.$router.go(-1)
              })
              .catch(() => {
                this.subLoading = false
              })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      } else {
        this.$refs.form.validate((valid) => {
          if (valid) {
            this.subLoading = true
            goodsSave({
              param
            })
              .then((res) => {
                if (res.errorCode !== '000000') return
                this.subLoading = false
                this.$message.success('新增成功')
                this.$router.go(-1)
              })
              .catch(() => {
                this.subLoading = false
              })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      }
    },
    // 返回上一页
    goBack() {
      this.$router.replace(`/application/varietySet?id=${this.goodsRestaurantId}`)
    }
  }
}
</script>

<style lang="scss" scoped>
@import "@/styles/variables.scss";
.device-uploader {
  width: 80px;
  height: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fff;
  cursor: pointer;
  border: 1px dashed #ccc;
  border-radius: 8px;
  transition: all 0.3s;
  margin-right: 20px;
  &:hover {
    border-color: $menuActive;
    .uploader-icon {
      color: $menuActive;
    }
  }
  ::v-deep .el-upload {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    .file {
      width: 100%;
      height: 100%;
      position: absolute;
      top: 0;
      left: 0;
      background-size: contain;
      background-position: center;
      background-repeat: no-repeat;
      border-radius: 8px;
      display: flex;
      align-items: center;
      justify-content: center;
      .delete {
        background-color: rgba(0, 0, 0, 0.5);
        position: absolute;
        width: 100%;
        height: 100%;
        top: 0;
        left: 0;
        display: none;
        align-items: center;
        justify-content: center;
        .icon {
          color: #fff;
        }
      }
      &:hover {
        .delete {
          display: flex;
        }
      }
    }
  }
  .uploader-icon {
    color: #aaaaaa;
    font-size: 22px;
    transition: all 0.3s;
  }
}
</style>
